package org.smartercontext.contextmger.json.reader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * @author JuanPablo
 * @version 1.0
 * @creation_date 09 Mar 2014
 * This class allows read a JSON file from a URL and extract each item in the format.
 *		
 */
public class JSONReader implements IJSONReader{

	@Override
	public JSONObject readJSONfromURL(String url) throws IOException,
			JSONException {
		
		InputStream inputStream=new URL(url).openStream();
        
        BufferedReader reader=new BufferedReader(
                                new InputStreamReader(
                                    inputStream,Charset.forName("UTF-8")));
        
        String jsonText=convertJSONtoText(reader);
        JSONObject json=new JSONObject(jsonText);
        inputStream.close();
        
        return json;
	}

	@Override
	public String convertJSONtoText(Reader reader) throws IOException {
		
		StringBuilder builder=new StringBuilder();
        int cont;
        
        while((cont = reader.read())!= -1){
            builder.append((char)cont);
        }
        return builder.toString();
	}

}
